﻿using System;
using System.Collections.Generic;
using System.Windows.Forms;
using System.IO;
using Meijay.DaliUsb;

namespace DaliUsbDemo.UserInterface
{
    public partial class FrmMain : Form
    {
        public FrmGeneralApiTest frmGeneralApiTest = null;

        public FrmMain()
        {
            InitializeComponent();

            this.lblLoadDaliBusAccessDLL.Text = "";
            this.lblSearchDaliUsbInterfaces.Text = "";
        }
        private void FrmMain_Load(object sender, EventArgs e)
        {
            btnLoadDaliBusAccessDll_Click(this, null);

            btnSearchDaliUsbInterface_Click(this, null);

            
        }
        private void btnLoadDaliBusAccessDll_Click(object sender, EventArgs e)
        {
            try
            {
                if (DaliUsbInterfaceManager.CheckDllSupport(out int dllVersionNumber) )
                {
                    int dllVersionMajorNumber = dllVersionNumber / 10000;
                    int dllVersionMinorNumber = (dllVersionNumber - dllVersionMajorNumber * 10000) / 100;
                    int dllVersionPatchNumber = (dllVersionNumber - dllVersionMajorNumber * 10000 - dllVersionMinorNumber * 100);
                    Version dllVersion = new Version(dllVersionMajorNumber, dllVersionMinorNumber, dllVersionPatchNumber);
                    this.lblLoadDaliBusAccessDLL.Text = "DaliBusAccess25.dll版本: V" + dllVersion.ToString() + "。";
                    if (dllVersionNumber < 30300)
                    {
                        this.lblLoadDaliBusAccessDLL.Text += System.Environment.NewLine +
                            "无法使用DALI USB，DLL 版本低于3.3.0，请更新支持软件。";
                    }
                }
                else
                {
                    throw new Exception("无法加载DALIBusAccess支持DLL库!");
                }
 
            }
            catch (Exception ex)
            {
                this.lblLoadDaliBusAccessDLL.Text = ex.Message;
            }
        }

        private void btnSearchDaliUsbInterface_Click(object sender, EventArgs e)
        {
            this.btnSearchDaliUsbInterface.Enabled = false;
            // Only support DALI USB interface
            DaliUsbInterfaceManager.DiscoverInterfaces();

            // display found devices
            updateDaliUsbInterfacesFound();

            this.btnSearchDaliUsbInterface.Enabled = true;
        }

        private void updateDaliUsbInterfacesFound()
        {
            this.comboIfDali.Items.Clear();


            /* find available DALI interfaces */
            List<DaliUsbInterface> all1 = DaliUsbInterfaceManager.DaliUsbInterfaces.FindAll((Predicate<DaliUsbInterface>)(x => x.IfType == DaliUsbInterface.IF_TYPE));
            ///DaliUsbInterface iFace2 = DaliUsbInterfaceManager.DaliUsbInterfaces.Find((Predicate<DaliUsbInterface>)(x => x.IfType == DaliUsbInterface.IF_TYPE && x.UniqueName == this.settings.interfaces.daliInterface.iFaceUniqueName));

            if (all1.Count == 0)
            {
                DaliUsbInterface iFace1 = new DaliUsbInterface();
                iFace1.IfName = "无DALI接口设备";
                this.comboIfDali.Items.Add((object)iFace1);

                this.lblSearchDaliUsbInterfaces.Text = "没有发现 DALI USB 接口设备。";
                this.btnOpenGeneralApiTest.Enabled = false;
            }
            else
            {
                foreach (DaliUsbInterface iFace3 in all1)
                {
                    this.comboIfDali.Items.Add((object)iFace3);
                }
                ///this.lblSearchDaliUsbInterfaces.Text = all1.Count.ToString() + " DALI USB interface" + (all1.Count > 1 ? "s" : "") + " found.";
                this.lblSearchDaliUsbInterfaces.Text = "发现 " + all1.Count.ToString() + " 个 DALI USB 接口设备。";
                this.btnOpenGeneralApiTest.Enabled = true;
            }
            this.comboIfDali.DisplayMember = "UniqueName";
            this.comboIfDali.ValueMember = "UniqueId";
            ///this.comboIfDali.SelectedItem = (object)iFace2;
            if (this.comboIfDali.SelectedIndex == -1)
            {
                this.comboIfDali.SelectedIndex = 0;
            }

        }

        private void btnOpenGeneralApiTest_Click(object sender, EventArgs e)
        {

            // open port here, only show API test form when port is sucessfully opened
            // open and get DALI USB interface Handle
            DaliUsbInterface SelectedIf = (DaliUsbInterface)this.comboIfDali.SelectedItem;
            if (SelectedIf != null)
            {
                // Load DLL again to avoid DaliBusServer no running issue
                DaliUsbInterfaceManager.DiscoverInterfaces();

                // try open selected interface
                ;

                // add handle checking, if handle < 0, quit
                // -1: PortNotAvailable
                // -3: NoServer
                DaliUsbResult result = DaliUsbInterface.OpenPort(SelectedIf);
                if (result == DaliUsbResult.OK)
                {
                    // open the selected interface, this should be done quickly because DaliBusServer may quit if without connection after 5secs
                    if (frmGeneralApiTest == null || frmGeneralApiTest.IsDisposed)
                    {
                        frmGeneralApiTest = new FrmGeneralApiTest();
                    }

                    frmGeneralApiTest.SelectedIf = SelectedIf;
                    frmGeneralApiTest.SelectedHandle = SelectedIf.IfHandle;
                    frmGeneralApiTest.ReturnForm = this;
                    frmGeneralApiTest.Text = SelectedIf.UniqueName + " - API 测试";
                    frmGeneralApiTest.Show();
                    this.Hide();
                }
                else if(result == DaliUsbResult.PortNotAvailable)  // DALI USB device may be disconnected
                {
                    MessageBox.Show(this, "所选设备可能已断开，请检查重试！", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
                else if(result == DaliUsbResult.DaliBusServerNotRunning)      // DaliBusServer may have quit without connection in 5secs
                {
                    MessageBox.Show(this, "DaliBusServer不在运行，请搜索设备后重试！", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
                else                                                           // Unknown ...
                {
                    MessageBox.Show(this, "无法打开设备！", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
            }


        }

    }
}
